import { useDrawer } from '@/utils/hooks'
import { useRequest } from 'ahooks'
import {
  Button, Divider, Image, message, Table, Tag,
} from 'antd'
import {
  FC, useCallback, useEffect, useMemo, useState,
} from 'react'
import styled from 'styled-components'
import { getFoodDetailApi, getFoodItemDetailApi, getFoodNameListApi } from '../../api/food'
import AppDrawer from './AppDrawer'

const StyledDetailContenier = styled.div`
padding: 50px 50px;
`
const AppFoodDetail: FC = () => {
  const [count, setCount] = useState(1)
  const [limitNum, setLimitNum] = useState(10)
  const { data: list = [], loading, run: getList = (count:number, pagesize:number) => []} = useRequest<any, []>(() => getFoodDetailApi(count, limitNum),{
    manual:true
  })
  const [ total, setTotal ] = useState(0)
  const handlePageChange = useCallback((page: number, pageSize: number) => {
    setCount(page)
    setLimitNum(pageSize)
  }, [])

  const pagination = useMemo(() => ({
    current: count,
    pageSize: limitNum,
    total:total,
    onChange: handlePageChange,
  }), [count, limitNum, list, handlePageChange, total])


  const getData = useCallback(async() => {
    try {
      const res = await getFoodNameListApi()
      setTotal(res.length)
    } catch (error) {
      console.log(error)
    }
  },[])

  useEffect(() => {
    getData()
    getList(count, limitNum)
  }, [count, limitNum])
  useEffect(() => {
    if(list){
      message.success('获取菜品档案成功！')
    }
  }, [])

  //单个菜品详细信息
  const { foodId, open, toggole, handleOnChange } = useDrawer()
  const columns = useMemo(() => ([
    {
      title: '菜名',
      dataIndex: 'foodName',
      ellipsis: true,
      width: 150,
    },
    {
      title: '描述',
      dataIndex: 'foodDesc',
      ellipsis: true,
      width: 150,
    },
    {
      title: '图片',
      dataIndex: 'img1',
      width: 150,
      render: (text: string) => (
        <Image
          width={ 100 }
          src={ text }
        />
      ),
    },
    {
      title: '价格',
      dataIndex: 'foodOrigincePrice',
    },
    {
      title: '类别',
      dataIndex: 'foodCategory',
      width: 130,
      render: (text: string) => <Tag color="#108ee9">{ text }</Tag>,
      align: 'center',
    },
    {
      title: '操作',
      width: 100,
      render: (_:string, record: any) => (
        <Button type="link" onClick={() => handleOnChange(record.foodId)}>查看</Button>
      ),
    },
  ]), [])

  return (
    <StyledDetailContenier>
      <h1>菜品档案</h1>
      <Divider />
      <Table loading={ loading } pagination={ pagination } dataSource={ list|| [] } rowKey="foodId" columns={ columns } />
      <AppDrawer foodId={foodId} onClose={ toggole } open={open}></AppDrawer>
    </StyledDetailContenier>
  )
}

export default AppFoodDetail
